<template>
    <!-- 搜索部分 -->
    <div class="search-box">
        <el-row type="flex" justify="space-between">
            <el-col :span="6">
                <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>&nbsp;添加干预记录</el-button>
            </el-col>
            <el-col :span="18">
                <el-form :inline="true" :model="searchInfo" style="text-align: right;">
                    <el-form-item label="用户名">
                        <el-input v-model.trim="searchInfo.user" placeholder="请输入用户名" style="width: 120px" />
                    </el-form-item>
                    <el-form-item label="干预等级">
                        <el-select v-model="searchInfo.level" placeholder="请选择" style="width: 120px">
                            <el-option label="全部" value=""></el-option>
                            <el-option v-for="l in levelOptions" :key="l" :label="l" :value="l" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="干预问题">
                        <el-select v-model="searchInfo.issue" placeholder="请选择" style="width: 120px">
                            <el-option label="全部" value=""></el-option>
                            <el-option v-for="i in issueOptions" :key="i" :label="i" :value="i" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="干预程度">
                        <el-select v-model="searchInfo.degree" placeholder="请选择" style="width: 120px">
                            <el-option label="全部" value=""></el-option>
                            <el-option v-for="d in degreeOptions" :key="d" :label="d" :value="d" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="search">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
    <!-- 表格部分 -->
    <div class="table-box">
        <el-table :data="currentTableData" style="width: 100%" height="400px" :header-cell-style="{ 'background-color': '#f5f7fa' }">
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="organization" label="组织结构" min-width="180" />
            <el-table-column prop="level" label="干预等级" width="120" />
            <el-table-column prop="issue" label="干预问题" min-width="150" />
            <el-table-column prop="duration" label="干预时长(小时)" width="150" />
            <el-table-column prop="degree" label="干预程度" width="120" />
            <el-table-column prop="recordTime" label="记录时间" width="180" />
            <el-table-column prop="recorder" label="记录人" width="100" />
            <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 添加/编辑记录对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
            <el-form-item label="姓名" prop="name">
                 <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="组织结构" prop="organization">
                <el-input v-model="form.organization" placeholder="请输入组织结构" />
            </el-form-item>
            <el-form-item label="干预等级" prop="level">
                <el-select v-model="form.level" placeholder="请选择干预等级">
                    <el-option v-for="l in levelOptions" :key="l" :label="l" :value="l" />
                </el-select>
            </el-form-item>
            <el-form-item label="干预问题" prop="issue">
                <el-select v-model="form.issue" placeholder="请选择干预问题">
                    <el-option v-for="i in issueOptions" :key="i" :label="i" :value="i" />
                </el-select>
            </el-form-item>
            <el-form-item label="干预时长(小时)" prop="duration">
                <el-input-number v-model="form.duration" :min="0" />
            </el-form-item>
            <el-form-item label="干预程度" prop="degree">
                <el-select v-model="form.degree" placeholder="请选择干预程度">
                    <el-option v-for="d in degreeOptions" :key="d" :label="d" :value="d" />
                </el-select>
            </el-form-item>
            <el-form-item label="记录时间" prop="recordTime">
                <el-date-picker v-model="form.recordTime" type="datetime" placeholder="选择记录时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="记录人" prop="recorder">
                <el-input v-model="form.recorder" placeholder="请输入记录人" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 分页部分 -->
    <div class="page-box">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="currentPageSize"
            :page-sizes="[10, 20, 30, 50]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const tableData = ref([]);
const tableDataCopy = ref([]);
const currentTableData = ref([]);
const currentPage = ref(1);
const currentPageSize = ref(10);
const searchInfo = ref({ user: '', level: '', issue: '', degree: '' });

const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);

const form = ref({
    id: null,
    name: '',
    organization: '',
    level: '',
    issue: '',
    duration: 0,
    degree: '',
    recordTime: '',
    recorder: ''
});

const rules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    organization: [{ required: true, message: '请输入组织结构', trigger: 'blur' }],
    level: [{ required: true, message: '请选择干预等级', trigger: 'change' }],
    issue: [{ required: true, message: '请选择干预问题', trigger: 'change' }],
    duration: [{ required: true, message: '请输入干预时长', trigger: 'blur' }],
    degree: [{ required: true, message: '请选择干预程度', trigger: 'change' }],
    recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }],
    recorder: [{ required: true, message: '请输入记录人', trigger: 'blur' }]
};

const levelOptions = ['一级干预', '二级干预', '三级干预'];
const issueOptions = ['学业压力', '家庭关系', '人际交往', '自我认识', '情绪管理', '个人成长', '职业生涯', '亲子关系', '心理健康', '睡眠障碍', '其他'];
const degreeOptions = ['轻微', '中等', '较重', '严重', '危重'];

const handleSizeChange = (newPageSize) => {
  currentPageSize.value = newPageSize;
  updateCurrentTableData();
}
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  updateCurrentTableData();
}

const updateCurrentTableData = () => {
    const start = (currentPage.value - 1) * currentPageSize.value
    const end = start + currentPageSize.value
    currentTableData.value = tableData.value.slice(start, end)
}

const search = () => {
    tableData.value = tableDataCopy.value.filter(item => {
        const userMatch = searchInfo.value.user ? item.name.includes(searchInfo.value.user) : true;
        const levelMatch = searchInfo.value.level ? item.level === searchInfo.value.level : true;
        const issueMatch = searchInfo.value.issue ? item.issue === searchInfo.value.issue : true;
        const degreeMatch = searchInfo.value.degree ? item.degree === searchInfo.value.degree : true;
        return userMatch && levelMatch && issueMatch && degreeMatch;
    });
    currentPage.value = 1;
    updateCurrentTableData();
}
const reset = () => {
  searchInfo.value = { user: '', level: '', issue: '', degree: '' }
  tableData.value = [...tableDataCopy.value];
  currentPage.value = 1;
  updateCurrentTableData();
}

const loadData = () => {
    const storedData = sessionStorage.getItem('interventionRecords');
    if (storedData) {
        tableData.value = JSON.parse(storedData);
    } else {
        // Mock data
        tableData.value = [
            {
                id: 1,
                name: '学生B',
                organization: 'XX学院XX班',
                level: '一级干预',
                issue: '学业压力',
                duration: 1,
                degree: '轻微',
                recordTime: '2023-11-02 14:00:00',
                recorder: '记录人A'
            }
        ];
        sessionStorage.setItem('interventionRecords', JSON.stringify(tableData.value));
    }
    tableDataCopy.value = [...tableData.value];
};

onMounted(() => {
    loadData();
    updateCurrentTableData();
});

const handleAdd = () => {
    dialogTitle.value = '添加干预记录';
    form.value = {
        id: null,
        name: '',
        organization: '',
        level: '',
        issue: '',
        duration: 0,
        degree: '',
        recordTime: '',
        recorder: ''
    };
    dialogVisible.value = true;
};

const handleEdit = (row) => {
    dialogTitle.value = '编辑干预记录';
    form.value = { ...row };
    dialogVisible.value = true;
};

const save = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            const record = { ...form.value };
            if (record.id) {
                // Edit
                const index = tableData.value.findIndex(item => item.id === record.id);
                if (index !== -1) {
                    tableData.value.splice(index, 1, record);
                }
            } else {
                // Add
                record.id = Date.now();
                tableData.value.unshift(record);
            }
            sessionStorage.setItem('interventionRecords', JSON.stringify(tableData.value));
            tableDataCopy.value = [...tableData.value];
            updateCurrentTableData();
            ElMessage.success('保存成功');
            dialogVisible.value = false;
        } else {
            ElMessage.error('请填写所有必填项');
            return false;
        }
    });
};

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = tableData.value.findIndex(item => item.id === row.id);
        if (index !== -1) {
            tableData.value.splice(index, 1);
        }
        sessionStorage.setItem('interventionRecords', JSON.stringify(tableData.value));
        tableDataCopy.value = [...tableData.value];
        updateCurrentTableData();
        ElMessage.success('删除成功');
    }).catch(() => {
        // a
    });
};

</script>

<style scoped>
.search-box {
    padding: 10px 0px 10px 10px;
}
.table-box {
    padding-left: 10px;
}
.page-box {
    display: flex;
    justify-content: center;
    padding-top: 10px;
}
</style>
